import React from "react";
import Header from "./component/Header/Header";
import Main from "./component/Main/Main";
import Footer from "./component/Footer/Footer";
import "./App.css"

export default class App extends React.Component {
    constructor(props) {
        super(props)
        // 状态提升：将数据放在App组件中，然后使用props传递数据给子组件
        this.state = {
            todos: JSON.parse(localStorage.getItem("todos")) || [
                {id: "1", name: "吃饭", done: true},
                {id: "2", name: "睡觉", done: true},
                {id: "3", name: "打豆豆", done: true},
                {id: "4", name: "逛街", done: true},
            ]
        }
    }

    // 添加一个todo的方法
    addTodo = (todoObject) => {
        // 拿到原先的todos数组
        const {todos} = this.state
        // 从原先的数组中查找是否和新添加的todo重复
        const result = todos.find(todo => todo.name === todoObject.name)
        // 如果重复则不添加todo
        if (result) return alert("您添加的todo重复了")
        // 设置一个新的todos数组
        this.setState({todos: [todoObject, ...todos]})
    }

    // 修改一个todo的方法
    changeTodo = ({done, id}) => {
        const currentTodo = this.state.todos.find(todo => todo.id === id)
        currentTodo.done = done
        this.setState({
            todos: this.state.todos
        })
    }

    // 删除一个todo的方法
    deleteTodo = (id) => {
        const {todos} = this.state
        const currentIndex = this.state.todos.findIndex(todo => todo.id === id)
        todos.splice(currentIndex, 1)
        this.setState({
            todos
        })
    }

    // 删除选中的todo
    deleteCheckedTodo = () => {
        const todos = this.state.todos.filter(todo => !todo.done)
        this.setState({todos})
    }

    //全选和取消全选的方法
    changeAllChecked = (done) => {
        const {todos} = this.state
        const newTodos = todos.map(todo => ({...todo, done}))
        this.setState({todos: newTodos})
    }

    render() {
        const {todos} = this.state
        localStorage.setItem("todos", JSON.stringify(todos))
        return (
            <div className="app layui-anim layui-anim-up">
                <div className="layui-panel">
                    {/*将addTodo方法传递给子组件用于子组件向父组件传递数据*/}
                    <Header addTodo={this.addTodo}></Header>
                    {/*将App组件中的todos列表使用props传递给Main组件*/}
                    <Main todos={todos} changeTodo={this.changeTodo} deleteTodo={this.deleteTodo}></Main>
                    <Footer todos={todos} deleteCheckedTodo={this.deleteCheckedTodo} changeAllChecked={this.changeAllChecked}></Footer>
                </div>
            </div>
        )
    }
}